package com.smmisia.shop.controller;

import com.smmisia.common.Result.Result;
import com.smmisia.shop.model.TradeOrderVO;
import com.smmisia.shop.model.dto.OrderStreamDTO;
import com.smmisia.shop.param.BuyParam;
import com.smmisia.shop.param.CancelParam;
import com.smmisia.shop.request.InventoryRequest;
import com.smmisia.shop.response.ProductInventoryResponse;
import com.smmisia.shop.service.ProductInventoryStreamService;
import com.smmisia.shop.service.TradeOrderService;
import io.lettuce.core.RedisClient;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/trade")
@Tag(name = "订单管理")
public class TradeController {

    @Autowired
    private TradeOrderService tradeOrderService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ProductInventoryStreamService productInventoryStreamService;

    /**
     * 下单
     * @param buyParam
     * @return
     */
    @PostMapping("/buy")
    @Operation(summary = "下单")
    public Result<OrderStreamDTO> buy(@Valid @RequestBody BuyParam buyParam){
        Integer cow = (Integer) redissonClient.getBucket("pd:inventory:1").get();
        log.info("库存:{}", cow);
//        InventoryRequest inventoryRequest = new InventoryRequest();
//        inventoryRequest.setProductId(buyParam.getProductId());
//        inventoryRequest.setInventory(1000);
//        inventoryRequest.setIdentifier(buyParam.getProductId());
//        ProductInventoryResponse init = productInventoryStreamService.init(inventoryRequest);
        return tradeOrderService.buy(buyParam);
    }

    /**
     * 获取订单列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    @Operation(summary = "订单列表")
    public Result<TradeOrderVO> orderList(@Valid @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize){
        return tradeOrderService.orderList(pageNum, pageSize);
    }

    /**
     *
     * 取消订单
     * @param cancelParam
     * @return
     */
    @PostMapping("/cancel")
    @Operation(summary = "取消订单")
    public Result<Boolean> cancel(@Valid @RequestBody CancelParam cancelParam){
        return tradeOrderService.cancel(cancelParam);
    }

    /**
     * 订单详情
     * @param orderId
     * @return
     */
    @GetMapping("/orderDetail")
    @Operation(summary = "订单详情")
    public Result<TradeOrderVO> orderDetail(@Valid @NotNull(message = "订单ID不能为空") String orderId) {
        return tradeOrderService.orderDetail(orderId);
    }
}
